package com.crk.yiyuanguahao.service.impl;



import com.crk.yiyuanguahao.dao.DoctorDao;
import com.crk.yiyuanguahao.dao.RoleAuthDao;
import com.crk.yiyuanguahao.dao.RoleDao;
import com.crk.yiyuanguahao.dao.UserDao;
import com.crk.yiyuanguahao.entity.Doctor;
import com.crk.yiyuanguahao.entity.Role;
import com.crk.yiyuanguahao.entity.RoleAuth;
import com.crk.yiyuanguahao.entity.User;
import com.crk.yiyuanguahao.service.RoleAuthService;
import com.crk.yiyuanguahao.service.UserService;
import com.crk.yiyuanguahao.util.Page;
import com.crk.yiyuanguahao.util.ResponseEnum;
import com.crk.yiyuanguahao.util.ResponseResult;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author: 程荣凯
 * @Date: 2019/2/27 14:47
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {
    /**
     * 用户操作
     */
    @Autowired
    UserDao userDao;
    @Autowired
    RoleAuthService roleAuthService;
    @Autowired
    RoleDao roleDao;
    @Autowired
    DoctorDao doctorDao;
    @Autowired
    RoleAuthDao roleAuthDao;



    private final static String DEFAULT_PWD = "123456";

    /**
     * 获取所有用户
     *
     * @return 用户列表
     */
    @Override
    public List<User> getAllUser() {
        return userDao.selectAll();
    }

    /**
     * 保存用户
     *
     * @param user 用户对象
     * @return
     */
    @Override
    public ResponseResult saveUser(User user) {
        if (null != user){
            int result = 0;
            if(user.getId() == null){
                user.setCreateTime(new Date());
                User userinfo = (User) SecurityUtils.getSubject().getPrincipal();
                user.setCreator(userinfo.getId());
                user.setUpdateTime(new Date());
                user.setUpdator(userinfo.getId());
                user.setStatus((short)1);
                user.setPwd(DEFAULT_PWD);
                user.setSalt(UUID.randomUUID().toString());
                result = userDao.insert(user);
            }else{
                user.setUpdateTime(new Date());
                User userinfo = (User) SecurityUtils.getSubject().getPrincipal();
                user.setUpdator(userinfo.getId());
                result = userDao.updateByPrimaryKey(user);

            }
            if (result>0){
                return ResponseResult.success(user);
            }else{
                return ResponseResult.fail();
            }
        }else {
            return ResponseResult.fail();
        }
    }

    /**
     * 根据用户名或手机号查询用户信息
     *
     * @param userName 用户名或手机号
     * @return
     */
    @Override
    public ResponseResult getUserByNameOrPhone(String userName) {
        return null;

    }




    /**
     * @param userId
     * @param status
     * @return
     */
    @Override
    public ResponseResult changeStatus(Integer userId, Integer status) {
        int result = userDao.changeStatus(userId,status);
        if (result>0){
            return ResponseResult.success();
        }else{
            return ResponseResult.fail();
        }
    }


    /**
     * 修改密码
     *
     * @param oldPwd 旧密码
     * @param newPwd 新密码
     * @return
     */
    @Override
    public ResponseResult changePassword(String oldPwd, String newPwd) {
        User userInfo = (User) SecurityUtils.getSubject().getPrincipal();
//        oldPwd = EncryptedUtil.generate(oldPwd, userInfo.getSalt());
        if (!oldPwd.equals(userInfo.getPwd())){
            return ResponseResult.fail(ResponseEnum.OLDPWD_ERROR);
        }
//        String salt = EncryptedUtil.getUUID();
//        String subPwd = EncryptedUtil.generate(newPwd, salt);
//        userInfo.setSalt(salt);
//        userInfo.setPwd(subPwd);
        userInfo.setUpdateTime(new Date());
        userInfo.setUpdator(userInfo.getId());
        int count = userDao.updateByPrimaryKey(userInfo);
        if (count>0){
            return ResponseResult.success();
        }else{
            return ResponseResult.fail();
        }
    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult deleteUser(Integer userId) {
        int result = userDao.deleteByPrimaryKey(userId);
        if (result > 0){
            return ResponseResult.success();
        }else{
            return ResponseResult.fail();
        }
    }

    /**
     * 查询用户列表（分页）
     *
     * @param userName
     * @param orderBy
     * @param currentPage
     * @param size
     * @return
     */
    @Override
    public ResponseResult getSysUserList(String userName,String keyword, String orderBy, Integer currentPage, Integer size) {
        Integer count = userDao.countSysUserList(userName,keyword);
        Page page = new Page();
        page.setAllRow(count);
        page.setCurrentPage(currentPage);
        page.setSize(size);
        List<User> userList = userDao.getSysUserList(userName,keyword,orderBy,page.getStart(),page.getSize());
        return ResponseResult.success(userList,page);
    }

    /**
     * 根据ID查询用户
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult getSysUserById(Integer userId) {
        User user = userDao.getSysUserById(userId);
        return ResponseResult.success(user);
    }

    /**
     * 重置密码
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult resetPwd(Integer userId) {
        User userInfo = (User) SecurityUtils.getSubject().getPrincipal();

        User user = new User();
//        String salt =EncryptedUtil.getSalt();
//        String pwd = EncryptedUtil.generate(EncryptedUtil.md5Hex(DEFAULT_PWD),salt);
//        user.setSalt(salt);
//        user.setPwd(pwd);
        user.setId(userId);
        user.setUpdator(userInfo.getId());
        user.setUpdateTime(new Date());
        int count = userDao.updateByPrimaryKey(user);
        if (count>0){
            return ResponseResult.success();
        }else{
            return ResponseResult.fail();
        }
    }

    /**
     * 根据用户ID查询包含的角色列表
     *
     * @param id
     * @return
     */
    @Override
    public List<Role> getRoleList(Integer id) {
        return userDao.getRoleList(id);
    }

    /**
     * 根据用户名查询用户
     *
     * @param userName
     * @return
     */
    @Override
    public User findByUsername(String userName) {
        return userDao.findByUsername(userName);
    }

    @Override
    public ResponseResult register(String userName, String phone, String email,String pwd, int userType, String doctorCode) {
//        医生注册
        if (userType == 1){
            if (StringUtils.isEmpty(doctorCode)){
                return ResponseResult.fail(ResponseEnum.PARAM_ERROR);
            }
            Doctor doctor = doctorDao.selectDoctorByCode(doctorCode);
            if (null == doctor){
                return ResponseResult.fail(ResponseEnum.DOCTOR_UNEXIST_ERROR);
            }
        }
        User user = new User();
        user.setUserName(userName);
        user.setPhone(phone);
        user.setEmail(email);
        user.setPwd(pwd);
        user.setDoctorCode(doctorCode);
        user.setCreator(1);
        user.setUpdator(1);
        user.setStatus((short)1);
        user.setUserType(userType);
        user.setSalt(UUID.randomUUID().toString());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        int insert = userDao.insert(user);
        if (insert > 0){
            RoleAuth roleAuth = new RoleAuth();
            roleAuth.setPartyId(user.getId());
            roleAuth.setPartyType((short)1);
            roleAuth.setRoleId(getRoleByType(userType));
            roleAuth.setStatus((short)1);
            roleAuth.setCreateTime(new Date());
            roleAuth.setUpdateTime(new Date());
            roleAuth.setCreator(1);
            roleAuth.setUpdator(1);
            int result = roleAuthDao.insert(roleAuth);
            if (result > 0 ){
                return ResponseResult.success();
            }else{
                return ResponseResult.fail();
            }

        }else{
            return ResponseResult.fail();
        }

    }



    /**
     * 根据用户类型查询角色ID
     * @param userType
     * @return
     */
    private Integer getRoleByType(Integer userType){
        String roleCode = "doctor";
        switch (userType){
            case 1:roleCode = "doctor";break;
            case 2:roleCode = "patient";break;
        }
        Role roleByCode = roleDao.getRoleByCode(roleCode);
        return roleByCode.getId();
    }
}
